package p.sglmsn.top.antiduplication.handle;

import cn.hutool.extra.spring.SpringUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import p.sglmsn.top.antiduplication.annotation.AntiDuplication;
import p.sglmsn.top.antiduplication.infe.UniqueCertificate;

import java.lang.reflect.Method;

/**
 * 去重的响应处理
 *
 * @author 王涛
 * @date 2021/02/01 11:32
 */
@RestControllerAdvice
@ConditionalOnBean({UniqueCertificate.class})
public class DuplicateRequestFilteringResponseHandle implements ResponseBodyAdvice<Object> {

    static final ThreadLocal<AntiDuplication> ANTI_DUPLICATION_THREAD_LOCAL = new InheritableThreadLocal<>();

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        Method method = returnType.getMethod();
        if (method != null) {
            boolean b = AnnotatedElementUtils.hasAnnotation(method, AntiDuplication.class);
            if (b) {
                ANTI_DUPLICATION_THREAD_LOCAL.set(method.getAnnotation(AntiDuplication.class));
                return true;
            }
        }
        return AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), AntiDuplication.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        AntiDuplication antiDuplication = ANTI_DUPLICATION_THREAD_LOCAL.get();
        ANTI_DUPLICATION_THREAD_LOCAL.remove();
        Class<? extends AntiDuplication.BeforeBodyWrite>[] classes = antiDuplication.beforeBodyWrite();
        if (classes.length > 0) {
            Class<? extends AntiDuplication.BeforeBodyWrite> aClass = classes[0];
            AntiDuplication.BeforeBodyWrite bean1 = SpringUtil.getBean(aClass);
            return bean1.handle(body);
        }
        return body;
    }
}
